package com.ymnet.myretrofit;

import android.app.Activity;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;



/**
 * Created by MajinBuu on 2018/1/8 0008.
 *
 * @overView ${todo}.
 */

public abstract class FileCallBack implements Callback<ResponseBody> {

    private String mDestFileDir;
    private String mDestFileName;
    private Activity mActivity;
    public FileCallBack(Activity activity, String destFileDir, String fileName) {
        mActivity = activity;
        mDestFileDir = destFileDir;
        mDestFileName = fileName;
    }

    public abstract void inProgress(float progress);

    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            saveFile(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public abstract void onFailure(Call<ResponseBody> call, Throwable t);

    private File saveFile(Response<ResponseBody> response) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        ResponseBody body = response.body();
        if (body == null) {
            Log.e("FileCallBack", "保存失败!");
            return null;
        }
        try {
            is = body.byteStream();
            final long total = body.contentLength();

            long sum = 0;

            File dir = new File(mDestFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, mDestFileName);
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final long finalSum = sum;
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        inProgress(finalSum * 1.0f / total);
                    }
                });
            }
            fos.flush();

            return file;

        } finally {
            try {
                if (body !=null) {
                    body.close();
                }
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }

        }
    }
}
